#coding:utf8
from django.shortcuts import render

# Create your views here.
#!/usr/bin/python
# -*-coding:utf-8-*-

from django.contrib.auth.decorators import login_required
from accounts.models import UserCreateForm
import json
import hashlib
import time
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.views.decorators.csrf import ensure_csrf_cookie
from userlog.function import SaveUserlog

@ensure_csrf_cookie
def login_view(request):
    u"登陆模块"
    cls=SaveUserlog()
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = auth.authenticate(username=username, password=password)
    if request.POST:
        # print username,password
        if user is not None and user.is_active:
            auth.login(request, user)
            cls(request,user=username,status=0) #登陆成功操作记录
            if not request.POST.get('remember_me', None):
                request.session.set_expiry(0)

            url =request.GET.get('next') or '/cmdb'
            return HttpResponseRedirect(url)
        else:
            print('login_error')
            {'login_err': "Wrong username or password"}
            cls(request,user=username,status=1) #登陆失败操作记录
            return render(request,'accounts/login.html', locals())
    else:
        if request.session.test_cookie_worked():  # 测套
            request.session.delete_test_cookie()  # 收套
            if request.GET.get('next') is None:
                url="/cmdb/"
            else:
                url=request.GET.get('next')
                return HttpResponseRedirect(url)

        else:
            return render(request,'accounts/login.html',locals())





def logout_view(request):
    #退出登录
    auth.logout(request)
    request.session.flush()
    return HttpResponseRedirect("/")



